package com.expert.miniapp.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.time.Duration;

/**
 * RestTemplateConfig - HTTP客户端配置
 *
 * 配置RestTemplate用于调用外部AI API
 * 使用分析报告AI的超时配置
 *
 * @author System
 * @since 2025-10-31
 */
@Configuration
public class RestTemplateConfig {

    @Autowired
    private AIAnalysisConfigProperties aiConfigProperties;

    /**
     * 创建RestTemplate Bean
     *
     * @param builder RestTemplateBuilder
     * @return 配置好的RestTemplate实例
     */
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        // 创建RestTemplate实例
        RestTemplate restTemplate = builder
                .setConnectTimeout(Duration.ofMillis(aiConfigProperties.getTimeout()))
                .setReadTimeout(Duration.ofMillis(aiConfigProperties.getTimeout()))
                .build();

        // 添加UTF-8编码的StringHttpMessageConverter
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        return restTemplate;
    }

    /**
     * 创建自定义的SimpleClientHttpRequestFactory
     * 设置更详细的超时配置
     *
     * @return SimpleClientHttpRequestFactory
     */
    @Bean
    public SimpleClientHttpRequestFactory clientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(aiConfigProperties.getTimeout());
        factory.setReadTimeout(aiConfigProperties.getTimeout());
        return factory;
    }
}
